#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
分页控件组件
用于在UI中显示分页信息和分页控制按钮
"""

import logging
from typing import Optional, Callable
from PyQt6.QtWidgets import (
    QWidget, QHBoxLayout, QPushButton, QLabel, 
    QComboBox, QSpinBox, QFrame
)
from PyQt6.QtCore import Qt, pyqtSignal
from PyQt6.QtGui import QFont

from src.utils.pagination_manager import PaginationManager, PaginationInfo

logger = logging.getLogger(__name__)

class PaginationWidget(QWidget):
    """分页控件"""
    
    # 信号定义
    page_changed = pyqtSignal(int)  # 页码改变信号
    page_size_changed = pyqtSignal(int)  # 每页大小改变信号
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.pagination_manager = PaginationManager()
        self.init_ui()
        self.update_ui()
    
    def init_ui(self):
        """初始化UI"""
        layout = QHBoxLayout(self)
        layout.setContentsMargins(5, 5, 5, 5)
        layout.setSpacing(10)
        
        # 分页信息标签
        self.info_label = QLabel("暂无数据")
        self.info_label.setMinimumWidth(200)
        layout.addWidget(self.info_label)
        
        layout.addStretch()
        
        # 每页大小选择
        self.page_size_label = QLabel("每页显示:")
        layout.addWidget(self.page_size_label)
        
        self.page_size_combo = QComboBox()
        self.page_size_combo.addItems(["10", "20", "50", "100"])
        self.page_size_combo.setCurrentText("20")
        self.page_size_combo.setMaximumWidth(80)
        self.page_size_combo.currentTextChanged.connect(self.on_page_size_changed)
        layout.addWidget(self.page_size_combo)
        
        # 分隔线
        separator = QFrame()
        separator.setFrameShape(QFrame.Shape.VLine)
        separator.setFrameShadow(QFrame.Shadow.Sunken)
        layout.addWidget(separator)
        
        # 第一页按钮
        self.first_page_btn = QPushButton("首页")
        self.first_page_btn.setMaximumWidth(50)
        self.first_page_btn.clicked.connect(self.go_first_page)
        layout.addWidget(self.first_page_btn)
        
        # 上一页按钮
        self.prev_page_btn = QPushButton("上一页")
        self.prev_page_btn.setMaximumWidth(60)
        self.prev_page_btn.clicked.connect(self.go_previous_page)
        layout.addWidget(self.prev_page_btn)
        
        # 页码输入
        self.page_label = QLabel("第")
        layout.addWidget(self.page_label)
        
        self.page_spin = QSpinBox()
        self.page_spin.setMinimum(1)
        self.page_spin.setMaximum(1)
        self.page_spin.setMaximumWidth(60)
        self.page_spin.valueChanged.connect(self.on_page_changed)
        layout.addWidget(self.page_spin)
        
        self.total_pages_label = QLabel("页")
        layout.addWidget(self.total_pages_label)
        
        # 下一页按钮
        self.next_page_btn = QPushButton("下一页")
        self.next_page_btn.setMaximumWidth(60)
        self.next_page_btn.clicked.connect(self.go_next_page)
        layout.addWidget(self.next_page_btn)
        
        # 最后一页按钮
        self.last_page_btn = QPushButton("末页")
        self.last_page_btn.setMaximumWidth(50)
        self.last_page_btn.clicked.connect(self.go_last_page)
        layout.addWidget(self.last_page_btn)
    
    def set_pagination_manager(self, pagination_manager: PaginationManager):
        """设置分页管理器"""
        self.pagination_manager = pagination_manager
        if self.pagination_manager:
            self.update_ui()
            logger.info("分页管理器已设置")
        else:
            logger.warning("分页管理器为空")
        
        # 设置样式
        self.setStyleSheet("""
            QPushButton {
                padding: 5px 10px;
                border: 1px solid #ccc;
                border-radius: 3px;
                background-color: #f8f9fa;
            }
            QPushButton:hover {
                background-color: #e9ecef;
            }
            QPushButton:pressed {
                background-color: #dee2e6;
            }
            QPushButton:disabled {
                background-color: #f1f3f4;
                color: #999;
                border-color: #ddd;
            }
            QLabel {
                color: #333;
            }
            QComboBox, QSpinBox {
                padding: 3px;
                border: 1px solid #ccc;
                border-radius: 3px;
                background-color: white;
            }
        """)
    

    
    def update_ui(self):
        """更新UI显示"""
        try:
            if not self.pagination_manager:
                return
            
            info = self.pagination_manager.get_pagination_info()
            
            # 更新信息标签
            self.info_label.setText(self.pagination_manager.get_page_info_text())
            
            # 更新页码输入框
            self.page_spin.setMaximum(info.total_pages)
            self.page_spin.setValue(info.current_page)
            
            # 更新总页数标签
            self.total_pages_label.setText(f"页，共 {info.total_pages} 页")
            
            # 更新按钮状态
            self.first_page_btn.setEnabled(info.has_previous)
            self.prev_page_btn.setEnabled(info.has_previous)
            self.next_page_btn.setEnabled(info.has_next)
            self.last_page_btn.setEnabled(info.has_next)
            
            # 更新每页大小选择
            current_page_size = str(self.pagination_manager.page_size)
            if current_page_size not in [self.page_size_combo.itemText(i) for i in range(self.page_size_combo.count())]:
                self.page_size_combo.addItem(current_page_size)
            self.page_size_combo.setCurrentText(current_page_size)
            
        except Exception as e:
            logger.error(f"更新分页UI失败: {e}")
    
    def go_first_page(self):
        """跳转到第一页"""
        if self.pagination_manager.first_page():
            self.page_changed.emit(self.pagination_manager.current_page)
            self.update_ui()
    
    def go_previous_page(self):
        """跳转到上一页"""
        if self.pagination_manager.previous_page():
            self.page_changed.emit(self.pagination_manager.current_page)
            self.update_ui()
    
    def go_next_page(self):
        """跳转到下一页"""
        if self.pagination_manager.next_page():
            self.page_changed.emit(self.pagination_manager.current_page)
            self.update_ui()
    
    def go_last_page(self):
        """跳转到最后一页"""
        if self.pagination_manager.last_page():
            self.page_changed.emit(self.pagination_manager.current_page)
            self.update_ui()
    
    def on_page_changed(self, page: int):
        """页码改变处理"""
        if self.pagination_manager.go_to_page(page):
            self.page_changed.emit(page)
            self.update_ui()
    
    def on_page_size_changed(self, page_size_text: str):
        """每页大小改变处理"""
        try:
            page_size = int(page_size_text)
            self.pagination_manager.set_page_size(page_size)
            self.page_size_changed.emit(page_size)
            self.update_ui()
        except ValueError:
            logger.error(f"无效的每页大小: {page_size_text}")
    

    
    def get_current_data(self) -> list:
        """获取当前页数据"""
        return self.pagination_manager.get_current_data()
    
    def get_pagination_info(self) -> PaginationInfo:
        """获取分页信息"""
        return self.pagination_manager.get_pagination_info()
